/**
 * Created by woody on 2017/2/28.
 */
import React from "react";
import {Alert, Image, ScrollView, Text, TextInput, TouchableOpacity, View} from "react-native";
import chjStyle from "../../CustomStyle";
import Util from "../Util";
import Toast from "react-native-root-toast";
import {Actions} from "react-native-router-flux";
import * as MineAction from "../../redux/action/Mine";

export default class Register extends React.Component {
    // 构造函数，可执行初始化操作
    constructor(props) {
        super(props);
        // 在ES6，在构造函数里初始化state
        this.state = {
            phoneNumber: '',
            passWord: '',
            passWord2: '',
            verifyCode: '',
            verifyTxt: '获取验证码',
            verifyDisabled: false,
            // timeTick:0,
        };
    }

    // 组件被加载时
    componentDidMount() {

    }

    // 组件即将被卸载时
    componentWillUnmount() {
        this.interval && clearInterval(this.interval);
    }

    // 组件被渲染时
    render() {
        return (
            <View style={chjStyle.mainContainer}>
                <ScrollView
                    style={chjStyle.recordContainer}>

                    <View style={[chjStyle.textItem, {height: chjStyle.getActualSizeInVertical(256)}]}>
                        <Image
                            style={{
                                position: 'absolute',
                                resizeMode: 'contain',
                                width: chjStyle.getActualSizeInHorizontal(375),
                                left: chjStyle.getActualSizeInHorizontal(187.5),
                                top: chjStyle.getActualSizeInVertical(50),
                            }}
                            source={require('../../../img/HeaderLogo.png')}/>
                    </View>

                    <View
                        style={[chjStyle.textItem]}>
                        <TextInput
                            placeholder="请输入手机号码"
                            ref='txtInputPhoneNumber'
                            autoCapitalize={this.props.autoCapitalize}
                            keyboardType='numeric'
                            maxLength={11}
                            onChangeText={this.onInputPhoneNumberChangeText.bind(this)}
                            underlineColorAndroid={'#00000000'}
                            style={[chjStyle.baseText, {
                                position: 'absolute',
                                color: '#303030',
                                textAlign: 'left',
                                backgroundColor: 'rgba(0, 0, 0, 0)',
                                textAlignVertical: 'center',
                                height: chjStyle.getActualSizeInVertical(128),
                                fontSize: chjStyle.getActualFontSize(30),
                                right: chjStyle.getActualSizeInHorizontal(30),
                                width: chjStyle.getActualSizeInHorizontal(690),
                            }]}/>
                    </View>

                    <View
                        style={[chjStyle.textItem]}>
                        <TextInput
                            placeholder="请输入密码"
                            ref='txtInputPassWord'
                            secureTextEntry={true}
                            autoCapitalize={this.props.autoCapitalize}
                            onChangeText={this.onInputPassWordChangeText.bind(this)}
                            underlineColorAndroid={'#00000000'}
                            style={[chjStyle.baseText, {
                                position: 'absolute',
                                color: '#303030',
                                textAlign: 'left',
                                backgroundColor: 'rgba(0, 0, 0, 0)',
                                textAlignVertical: 'center',
                                height: chjStyle.getActualSizeInVertical(128),
                                fontSize: chjStyle.getActualFontSize(30),
                                right: chjStyle.getActualSizeInHorizontal(30),
                                width: chjStyle.getActualSizeInHorizontal(690),
                            }]}/>
                    </View>


                    <View
                        style={[chjStyle.textItem]}>
                        <TextInput
                            placeholder="再次输入密码"
                            ref='txtInputPassWord2'
                            secureTextEntry={true}
                            autoCapitalize={this.props.autoCapitalize}
                            onChangeText={this.onInputPassWord2ChangeText.bind(this)}
                            underlineColorAndroid={'#00000000'}
                            style={[chjStyle.baseText, {
                                position: 'absolute',
                                color: '#303030',
                                textAlign: 'left',
                                backgroundColor: 'rgba(0, 0, 0, 0)',
                                textAlignVertical: 'center',
                                height: chjStyle.getActualSizeInVertical(128),
                                fontSize: chjStyle.getActualFontSize(30),
                                right: chjStyle.getActualSizeInHorizontal(30),
                                width: chjStyle.getActualSizeInHorizontal(690),
                            }]}/>
                    </View>

                    <View
                        style={[chjStyle.textItem]}>
                        <TextInput
                            placeholder="请输入验证码"
                            ref='txtInputVerifyCode'
                            autoCapitalize={this.props.autoCapitalize}
                            keyboardType='numeric'
                            maxLength={6}
                            onChangeText={this.onInputVerifyCodeChangeText.bind(this)}
                            underlineColorAndroid={'#00000000'}
                            style={[chjStyle.baseText, {
                                position: 'absolute',
                                color: '#303030',
                                textAlign: 'left',
                                backgroundColor: 'rgba(0, 0, 0, 0)',
                                textAlignVertical: 'center',
                                height: chjStyle.getActualSizeInVertical(128),
                                fontSize: chjStyle.getActualFontSize(30),
                                right: chjStyle.getActualSizeInHorizontal(30),
                                width: chjStyle.getActualSizeInHorizontal(690),
                            }]}/>

                        <TouchableOpacity
                            onPress={() => this.onClickedGetVerifyListener()}
                            ref='getVerifyCode'
                            style={{
                                position: 'absolute',
                                backgroundColor: '#ff971d',
                                top: chjStyle.getActualSizeInVertical(0),
                                right: chjStyle.getActualSizeInHorizontal(0),
                                width: chjStyle.getActualSizeInHorizontal(280),
                                height: chjStyle.getActualSizeInVertical(128),
                            }}>
                            <Text style={[chjStyle.baseText, {
                                backgroundColor: 'rgba(0,0,0,0)',
                                color: '#fff',
                                textAlign: 'center',
                                top: chjStyle.getActualFontSize(46)
                            }]}>{this.state.verifyTxt}</Text>
                        </TouchableOpacity>
                    </View>


                    <View
                        style={{height: chjStyle.getActualSizeInVertical(140)}}>
                        <TouchableOpacity
                            onPress={() => this.onClickedRegister()}
                            style={{
                                position: 'absolute',
                                backgroundColor: '#ffc93f',
                                borderRadius: 5,
                                borderTopWidth: 1,
                                borderLeftWidth: 1,
                                borderRightWidth: 1,
                                borderBottomWidth: 1,
                                borderColor: '#fff',
                                width: chjStyle.getActualSizeInHorizontal(700),
                                height: chjStyle.getActualSizeInVertical(100),
                                left: chjStyle.getActualSizeInHorizontal(25),
                                top: chjStyle.getActualSizeInVertical(40),
                            }}>
                            <Text style={[chjStyle.baseText, {
                                color: '#fff',
                                textAlign: 'center',
                                fontSize: chjStyle.getActualFontSize(40),
                                top: chjStyle.getActualSizeInVertical(24)
                            }]}>注册</Text>
                        </TouchableOpacity>
                    </View>

                </ScrollView>

                <TouchableOpacity onPress={() => Actions.pop()}
                                  style={{
                                      backgroundColor: '#00000000',
                                      position: 'absolute',
                                      left: chjStyle.getActualSizeInVertical(20),
                                      top: chjStyle.getActualSizeInVertical(72),
                                      width: chjStyle.getActualSizeInHorizontal(72),
                                      height: chjStyle.getActualSizeInVertical(72)
                                  }}>
                    <Image source={require('../../../img/back.png')}
                           resizeMode='contain'
                           style={{
                               width: chjStyle.getActualSizeInHorizontal(72),
                               height: chjStyle.getActualSizeInVertical(72)
                           }}/>
                </TouchableOpacity>

            </View>

        );
    }


    // 用户注册
    onClickedRegister() {
        if (this.state.phoneNumber === '' || this.state.verifyCode === '' || this.state.passWord === '' || this.state.passWord2 === '') {
            Alert.alert("错误", "请输入完整信息");
            return;
        }

        if (this.state.passWord !== this.state.passWord2) {
            Alert.alert("错误", "两次输入的密码不一致");
            return;
        }


        const params = {
            phone: this.state.phoneNumber,
            code: this.state.verifyCode,
            password: this.state.passWord,
            userid: null
        };

        // this.props.rootview.setLoadingVisible(true, '正在注册中');
        Util.postServer("user/reg", params, (result) => this.onRegisterSuccess(result), (msg) => this.onLoginFailed(msg));
    }

    // 注册成功回调
    onRegisterSuccess(result) {
        // this.props.rootview.setLoadingVisible(false, '');
        // Alert.alert('注册返回', JSON.stringify(result));

        if (result.status === '0') {
            const param = {
                id: result.data.user.userid,
                token: result.data.user.token,
                phone: result.data.user.phone,
                info: result.data.user,
            };

            Util.storage.save({
                key: 'users',
                id: '1000',
                rawData: param,
                expires: null
            });

            MineAction.userData(param);

            Toast.show("注册成功", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
            Actions.main();
        }
        else {
            Alert.alert("注册失败", result.msg);
        }

    }

    // 注册失败回调
    onLoginFailed(msg) {
        // this.props.rootview.setLoadingVisible(false, '');
        Toast.show(msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    }

    // 获取短信验证码
    onClickedGetVerifyListener() {
        if (!this.state.phoneNumber || this.state.phoneNumber.length < 11) {
            Alert.alert('请输入手机号');
            return;
        }

        if (this.state.verifyDisabled)
            return;

        this.state.verifyDisabled = true;
        this.interval && clearInterval(this.interval);
        this.cd = 60;
        this.interval = setInterval(
            () => {
                this.cd--;
                this.setState({
                    verifyTxt: this.cd === 0 ? '获取验证码' : this.cd + '秒',
                    verifyDisabled: this.cd !== 0
                });
                if (this.cd === 0) {
                    this.interval && clearInterval(this.interval);
                    this.interval = null;
                }
            }, 1000
        )

        const params = {
            phone: this.state.phoneNumber
        };
        Util.postServer('user/code', params, (result) => this.onGetVerifyCodeSuccess(result), (msg) => this.onGetVerifyCodeFailed(msg));
    }

    // tickTime(param)
    // {
    //     // var tick = timeTick + 1;
    //     // this.setState({ timeTick:tick });
    //     Alert.alert( "Title", param );
    // }


    onGetVerifyCodeSuccess(result) {
        if (result.status !== '0') {
            Toast.show(result.msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
        }
        else {
            Toast.show("短信验证码已发送", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
        }
    }

    onGetVerifyCodeFailed(msg) {
        Toast.show(msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    }

    onInputPhoneNumberChangeText(value) {
        this.state.phoneNumber = value;
    }

    onInputVerifyCodeChangeText(value) {
        this.state.verifyCode = value;
    }

    onInputPassWordChangeText(value) {
        this.state.passWord = value;
    }

    onInputPassWord2ChangeText(value) {
        this.state.passWord2 = value;
    }
}
